package com.jlt.web.account;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.google.common.collect.Sets;
import com.jlt.entity.account.Dept;
import com.jlt.entity.account.Group;
import com.jlt.entity.account.Post;
import com.jlt.entity.account.Role;
import com.jlt.entity.account.User;
import com.jlt.exception.ServiceException;
import com.jlt.service.account.AccountManager;
import com.jlt.web.CrudActionSupport;
import com.jlt.web.util.Struts2ActionUtils;

/**
 * 用户管理Action.
 * 
 * 
 * @author zhoutao
 */
// 定义URL映射对应/account/user.action
@Namespace("/account")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "user.action", type = "redirect") })
public class UserAction extends CrudActionSupport<User> {

	private static final long serialVersionUID = 1L;
	private static final String ENTITY_NAME = "用户";
	@Autowired
	private AccountManager accountManager;
	@Autowired
	private PasswordEncoder Md5PwdEncoder;
	// @Autowired
	// private ReflectionSaltSource Md5Salt;

	// -- 页面属性 --//
	private Long id;
	private User entity;
	private Page<User> page = new Page<User>(15);// 每页15条记录
	private String roleIds = "";
	private String deptIds = "";
	private String groupIds = "";
	private String postIds = "";

	// -- ModelDriven 与 Preparable函数 --//
	public void setId(Long id) {
		this.id = id;
	}

	public User getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = accountManager.getUser(id);
		} else {
			entity = new User();
			entity.setCreatedBy(SpringSecurityUtils.getCurrentUserName());
			entity.setCreatedTime(new Date());
			entity.setUpdatedBy(SpringSecurityUtils.getCurrentUserName());
			entity.setUpdatedTime(new Date());
		}
	}

	// -- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		page = accountManager.searchUser(page, filters);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		if(null==entity.getId()){
			String md5Pwd = Md5PwdEncoder.encodePassword(entity.getPassword(), entity.getLoginName());
			entity.setPassword(md5Pwd);
		}
		// 根据页面上的checkbox选择 整合User的Roles Set
		Set<Role> roleSet = Sets.newHashSet();
		Set<Dept> deptSet = Sets.newHashSet();
		Set<Post> postSet = Sets.newHashSet();
		Set<Group> groupSet = Sets.newHashSet();
		if (StringUtils.isNotBlank(roleIds)) {
			String roleIdsArray[] = roleIds.split(",");
			for (String roleId : roleIdsArray) {
				Role role = new Role();
				role.setId(Long.valueOf(roleId));
				roleSet.add(role);
			}
		}
		if (StringUtils.isNotBlank(deptIds)) {
			String deptIdsArray[] = deptIds.split(",");
			for (String deptId : deptIdsArray) {
				Dept dept = new Dept();
				dept.setId(Long.valueOf(deptId));
				deptSet.add(dept);
			}
		}
		if (StringUtils.isNotBlank(postIds)) {
			String postIdsArray[] = postIds.split(",");
			for (String postId : postIdsArray) {
				Post post = new Post();
				post.setId(Long.valueOf(postId));
				postSet.add(post);
			}
		}
		if (StringUtils.isNotBlank(groupIds)) {
			String groupIdsArray[] = groupIds.split(",");
			for (String groupId : groupIdsArray) {
				Group group = new Group();
				group.setId(Long.valueOf(groupId));
				groupSet.add(group);
			}
		}
		entity.setRoleSet(roleSet);
		entity.setDeptSet(deptSet);
		entity.setGroupSet(groupSet);
		entity.setPostSet(postSet);
		entity.setUpdatedBy(SpringSecurityUtils.getCurrentUserName());
		entity.setUpdatedTime();
		accountManager.saveUser(entity);
		Map<String, String> message = new HashMap<String, String>();
		message = Struts2ActionUtils.getDwzOperateMessage(Struts2ActionUtils.SAVE,
				Struts2ActionUtils.SUCCESSFUL, ENTITY_NAME,Struts2ActionUtils.CLOSE_CURRENT);
		Struts2Utils.renderJson(message);
		return null;
	}

	@Override
	public String delete() throws Exception {
		Map<String, String> message = new HashMap<String, String>();
		try {
			accountManager.deleteUser(id);
			message = Struts2ActionUtils.getDwzOperateMessage(Struts2ActionUtils.DELETE,
					Struts2ActionUtils.SUCCESSFUL, ENTITY_NAME);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			message = Struts2ActionUtils.getDwzOperateMessage(Struts2ActionUtils.DELETE,
					Struts2ActionUtils.FAILURE, ENTITY_NAME);
		}
		Struts2Utils.renderJson(message);
		return null;
	}

	// -- 其他Action函数 --//
	/**
	 * 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkLoginName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String newLoginName = request.getParameter("loginName");
		String oldLoginName = request.getParameter("oldLoginName");

		if (accountManager.isLoginNameUnique(newLoginName, oldLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	public String changePwd() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String rnewPassword = request.getParameter("rnewPassword");
		String username = SpringSecurityUtils.getCurrentUserName();
		
		User user = accountManager.findUserByLoginName(username);
		Map<String, String> message = new HashMap<String, String>();
		
		if(null!=user){
			if (StringUtils.isNotBlank(oldPassword) && StringUtils.equals(newPassword, rnewPassword)) {
				String oldMd5Pwd = Md5PwdEncoder.encodePassword(oldPassword, username);
				if (oldMd5Pwd.equals(user.getPassword())) {
					user.setPassword(Md5PwdEncoder.encodePassword(newPassword, username));
					 accountManager.saveUser(user);
					message.put("statusCode", "200");
					message.put("message", "修改密码成功，请重新登陆！");
				}else{
					message.put("statusCode", "300");
					message.put("message", "原密码错误，请重试！");
				}
			}else{
				message.put("statusCode", "300");
				message.put("message", "原密码或新密码错误，请重试！");
			}
		}else{
			message.put("statusCode", "300");
			message.put("message", "无此用户，请重试！");
		}

		message.put("callbackType", "closeCurrent");
		Struts2Utils.renderJson(message);
		return null;
	}

	// -- 页面属性访问函数 --//
	/**
	 * list页面显示用户分页列表.
	 */
	public Page<User> getPage() {
		return page;
	}

	public String getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(String roleIds) {
		this.roleIds = roleIds;
	}

	public String getDeptIds() {
		return deptIds;
	}

	public void setDeptIds(String deptIds) {
		this.deptIds = deptIds;
	}

	public String getGroupIds() {
		return groupIds;
	}

	public void setGroupIds(String groupIds) {
		this.groupIds = groupIds;
	}

	public String getPostIds() {
		return postIds;
	}

	public void setPostIds(String postIds) {
		this.postIds = postIds;
	}

}
